package String;


import java.util.ArrayDeque;

public class ReverseWords151 {
    public static void main(String[] args) {
        System.out.println(reverseWords(new String("  hello world ")));
    }
    public static String reverseWords(String s) {
        if (s == null) {
            return null;
        }
        char[] array = s.toCharArray();
        StringBuilder sb = new StringBuilder();
        ArrayDeque<String> stack = new ArrayDeque<>();
        int i = 0;
        while (array[i] == ' ') {
            i++;
        }
        while (i < array.length) {
            if (array[i] != ' ') {
                sb.append(array[i]);
            } else if (i < array.length-1 && array[i] == ' ' && array[i + 1] != ' ') {
                stack.push(sb.toString());
                stack.push(new String(" "));
                sb.delete(0, sb.length());
            }
            if(i == array.length-1){
                stack.push(sb.toString());
            }
            i++;
        }
        StringBuilder builder = new StringBuilder();
        for (String s1 : stack) {
            builder.append(s1);
        }
        return builder.toString();
    }
}
